package com.xiongyingqi.openfire;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

import org.xmpp.packet.Message;

import com.xiongyingqi.openfire.listener.MessageListener;
/**
 * 消息监听路由，当服务端有新消息传输则会通知本插件
 * 当有实例注册时就会调用@see com.xiongyingqi.openfire.listener.MessageListener.route(org.xmpp.packet.Message message)方法
 * 要捕获消息，请使用addMessageListener(MessageListener messageListener)方法注册
 * @author xiongyingqi
 */
public class MessageListenerRouter {
	private static Set<MessageListener> messageListeners;
	
	private static MessageListenerRouter messageListenerRouter;
	
	private MessageListenerRouter(){};
	/**
	 * 获取实例
	 * @return
	 */
	public synchronized static MessageListenerRouter getInstance(){
		if(messageListenerRouter == null){
			messageListenerRouter = new MessageListenerRouter();
//			messageListeners = new LinkedHashSet<MessageListener>();
		}
		return messageListenerRouter;
	}
	/**
	 * 注册消息事件监听
	 * @param messageListener
	 */
	public void addMessageListener(MessageListener messageListener){
		if(messageListener != null){
			if(messageListeners == null){
				messageListeners = new LinkedHashSet<MessageListener>();
			}
			messageListeners.add(messageListener);
		}
	}
	/**
	 * 取消消息监听
	 * @param messageListener
	 */
	public void removeMessageListener(MessageListener messageListener){
		if(messageListener != null && messageListeners != null){
			messageListeners.remove(messageListener);
		}
	}
	/**
	 * 递交消息拷贝
	 * @param message
	 */
	public void route(Message message){
		if(messageListeners != null && messageListeners.size() > 0){
			Iterator<MessageListener> messageIterator = messageListeners.iterator();
			for (Iterator iterator = messageIterator; iterator.hasNext();) {
				MessageListener messageListener = (MessageListener) iterator.next();
				messageListener.route(message);
			}
		}
//		new RouteThread(message.createCopy()).start();
	}
	/**
	 * 线程内递交消息
	 * @param message
	 */
	private void routInThread(Message message){
		if(messageListeners != null && messageListeners.size() > 0){
			Iterator<MessageListener> messageIterator = messageListeners.iterator();
			for (Iterator iterator = messageIterator; iterator.hasNext();) {
				MessageListener messageListener = (MessageListener) iterator.next();
				messageListener.route(message);
			}
		}
	}
	
	class RouteThread extends Thread{
		private Message message;
		private RouteThread(Message message){
			this.message = message;
		}
		@Override
		public void run() {
			routInThread(message);
		}
	}
//	public static void main(String[] args) {
//		Message message = new Message();
//		message.setFrom("a");
//		System.out.println(message.createCopy());
//	}
}
